﻿/* 
 * Rug.Cmd part of Rugland Console Framework
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 * 
 * Copyright (C) 2008 Phill Tew. All rights reserved.
 * 
 */

using System;
using System.Collections.Generic;
using System.Text;

namespace Rug.Cmd.Arguments
{    
    public class CommandLineSplitter
    {
        public static string[] SplitArguments(string commandLine)
        {            
            char[] parmChars = commandLine.ToCharArray();
            bool inDoubleQuote = false;
            bool lastCharIsEscapeChar = false;

            for (int index = 0; index < parmChars.Length; index++)
            {
                if (parmChars[index] == '"')
                {
                    if (!lastCharIsEscapeChar)
                    {
                        inDoubleQuote = !inDoubleQuote;
                        parmChars[index] = '\n';
                    }
                    else
                        lastCharIsEscapeChar = true; 
                }
                else if (parmChars[index] == '\\' && inDoubleQuote)
                {
                    lastCharIsEscapeChar = true; 
                }
                else if (!inDoubleQuote && parmChars[index] == ' ')
                {
                    parmChars[index] = '\n';
                    lastCharIsEscapeChar = false;
                }
                else
                    lastCharIsEscapeChar = false;
            }

            return (new string(parmChars)).Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
        }
    }
}